﻿import sys
import io

# 设置标准输出的编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


# Python 基础语法示例

# 1. 变量和数据类型
print("=== 变量和数据类型 ===")

# 数字类型
integer_var = 10           # 整数
float_var = 3.14          # 浮点数
complex_var = 1 + 2j      # 复数

print(f"整数: {integer_var}, 类型: {type(integer_var)}")
print(f"浮点数: {float_var}, 类型: {type(float_var)}")
print(f"复数: {complex_var}, 类型: {type(complex_var)}")

# 字符串类型
string_var = "Hello, Python!"
print(f"字符串: {string_var}, 类型: {type(string_var)}")

# 布尔类型
bool_true = True
bool_false = False
print(f"布尔值: {bool_true} 和 {bool_false}, 类型: {type(bool_true)}")

# 列表 - 有序，可变
list_var = [1, 2, 3, "a", "b", "c"]
print(f"列表: {list_var}, 类型: {type(list_var)}")

# 元组 - 有序，不可变
tuple_var = (1, 2, 3, "a", "b", "c")
print(f"元组: {tuple_var}, 类型: {type(tuple_var)}")

# 字典 - 键值对
dict_var = {"name": "Alice", "age": 25, "city": "Beijing"}
print(f"字典: {dict_var}, 类型: {type(dict_var)}")

# 集合 - 无序，不重复
set_var = {1, 2, 3, 3, 4, 5}
print(f"集合: {set_var}, 类型: {type(set_var)}")

print("\n")

# 2. 运算符
print("=== 运算符 ===")
a, b = 10, 3

# 算术运算符
print(f"{a} + {b} = {a + b}")  # 加法
print(f"{a} - {b} = {a - b}")  # 减法
print(f"{a} * {b} = {a * b}")  # 乘法
print(f"{a} / {b} = {a / b}")  # 除法
print(f"{a} % {b} = {a % b}")  # 取模
print(f"{a} ** {b} = {a ** b}")  # 幂运算
print(f"{a} // {b} = {a // b}")  # 整除

# 比较运算符
print(f"{a} == {b}: {a == b}")  # 等于
print(f"{a} != {b}: {a != b}")  # 不等于
print(f"{a} > {b}: {a > b}")    # 大于
print(f"{a} < {b}: {a < b}")    # 小于

# 逻辑运算符
x, y = True, False
print(f"{x} and {y}: {x and y}")  # 与
print(f"{x} or {y}: {x or y}")    # 或
print(f"not {x}: {not x}")        # 非

print("\n")

# 3. 控制结构
print("=== 控制结构 ===")

# if-elif-else 条件语句
score = 85
if score >= 90:
    print("成绩优秀")
elif score >= 80:
    print("成绩良好")
elif score >= 60:
    print("成绩及格")
else:
    print("成绩不及格")

# for 循环
print("for 循环示例:")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# while 循环
print("while 循环示例:")
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

print("\n")

# 4. 函数
print("=== 函数 ===")

# 定义函数
def greet(name):
    """简单的问候函数"""
    return f"Hello, {name}!"

# 调用函数
greeting = greet("Python Learner")
print(greeting)

# 带默认参数的函数
def power(base, exponent=2):
    """计算幂，默认指数为2"""
    return base ** exponent

print(f"5 squared: {power(5)}")
print(f"2 cubed: {power(2, 3)}")

print("\n")

# 5. 列表操作
print("=== 列表操作 ===")

numbers = [1, 2, 3, 4, 5]

# 添加元素
numbers.append(6)          # 在末尾添加
numbers.insert(0, 0)       # 在指定位置插入
print(f"After adding elements: {numbers}")

# 删除元素
numbers.pop()              # 删除末尾元素
numbers.remove(0)          # 删除指定元素
print(f"After removing elements: {numbers}")

# 列表切片
print(f"First three elements: {numbers[:3]}")
print(f"Last two elements: {numbers[-2:]}")
print(f"Reversed list: {numbers[::-1]}")

# 列表推导式
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")

print("\n")

# 6. 文件操作 (使用英文避免编码问题)
print("=== 文件操作 ===")

# 写入文件
with open("example.txt", "w") as f:
    f.write("This is line 1\n")
    f.write("This is line 2\n")

# 读取文件
with open("example.txt", "r") as f:
    content = f.read()
    print("File content:")
    print(content)

print("\n")

# 7. 异常处理
print("=== 异常处理 ===")

try:
    # 可能引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print(f"Result is: {result}")
finally:
    print("This code always executes")

print("\n")

# 8. 类和对象
print("=== 类和对象 ===")

class Dog:
    """A simple Dog class"""
    
    # 类属性
    species = "Canis familiaris"
    
    # 初始化方法
    def __init__(self, name, age):
        self.name = name  # 实例属性
        self.age = age
    
    # 实例方法
    def description(self):
        return f"{self.name} is {self.age} years old"
    
    def speak(self, sound):
        return f"{self.name} says {sound}"

# 创建实例
my_dog = Dog("Buddy", 5)
print(my_dog.description())
print(my_dog.speak("Woof Woof!"))

print("\nProgram execution completed!")